package com.udaos.modules.card.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.Service;
import com.udaos.models.card.Ud_card;
import com.udaos.models.card.Ud_card_review;
import com.udaos.models.card.Ud_wx_card;
import com.udaos.models.sys.Sys_user;
import com.udaos.models.wx.Wx_config;
import com.udaos.modules.base.enums.UserTypeEnum;
import com.udaos.modules.card.pojo.LandingPage;
import com.udaos.modules.card.utils.HttpUtils;
import com.udaos.modules.wx.services.WxConfigService;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import net.sf.json.JSONObject;

/**
 * 微信卡券Service 
 * @author Administrator
 */
@IocBean(args = { "refer:dao" })
public class UdWxCardService extends Service<Ud_wx_card>{
	public UdWxCardService(Dao dao) {
		setDao(dao);
	}
	
	@Inject
	private WxConfigService wxConfigService;
	@Inject
	private UdCardService cardService;
	@Inject
	private UdCardReviewService cardReviewService;
	
	
	/**
	 * 创建单个微信卡券模板的二维码
	 * @param card_id           微信卡券ID（此ID为微信生成的card_id）
	 * @param wxId			  	微信平台ID
	 * @param openid			指定领取者的openid，只有该用户能领取。bind_openid字段为true的卡券必须填写，非指定openid不必填写。
	 * @param expire_seconds	指定二维码的有效时间，范围是60 ~ 1800秒。不填默认为永久有效。
	 * @param is_unique_code	指定下发二维码，生成的二维码随机分配一个code，领取后不可再次扫描。填写true或false。默认false，注意填写该字段时，卡券须通过审核且库存不为0
	 * @param outer_id          领取场景值，用于领取渠道的数据统计，默认值为0，字段类型为整型，长度限制为60位数字。用户领取卡券后触发的事件推送中会带上此自定义场景值。
	 * @return
	 */
	public Object createWxSingleWithQrcode(String card_id,String wxId,@Param("openid") String openid,@Param("expire_seconds") Integer expire_seconds,@Param("is_unique_code") Boolean is_unique_code,@Param("outer_id") Integer outer_id){
		Map<String,Object> map=new HashMap<String,Object>();
		try {
			//1.组装数据
			Map<String,Object> cardMap=new HashMap<String,Object>();
			cardMap.put("card_id",card_id);
			if(null !=outer_id){
				cardMap.put("outer_id",outer_id);
			}
			if(null !=is_unique_code){
				cardMap.put("is_unique_code",is_unique_code);
			}
			if(null !=openid){
				cardMap.put("openid",openid);
			}
			Map<String,Object> actionInfoMap=new HashMap<String,Object>();
			actionInfoMap.put("card", cardMap);
			Map<String,Object> paramMap=new HashMap<String,Object>();
			paramMap.put("action_info", actionInfoMap);
			paramMap.put("action_name", "QR_CARD");
			if(null !=expire_seconds && expire_seconds>0){
				//判断是否大于1800
				if(expire_seconds>1800){
					expire_seconds=1800;
				}else if(expire_seconds>0 && expire_seconds<60){
					expire_seconds=60;
				}
				paramMap.put("expire_seconds",expire_seconds);
			}
			//2.发起请求
			WxMpService wxMpService=getWxMpService(wxId);
			String token=wxMpService.getAccessToken();
			
			System.out.println("=============="+JSONObject.fromObject(paramMap).toString());
			String url="https://api.weixin.qq.com/card/qrcode/create?access_token="+token;
			JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", JSONObject.fromObject(paramMap).toString());
			
			map.put("code", "1");
			map.put("message", "创建成功");
			map.put("data", jsonObject);
			return map;
		} catch (Exception e) {
			map.put("code", "0");
			map.put("message", e.getMessage());
			return map;
		}
	}
	

	/**
	 * 创建多个微信卡券模板的二维码
	 * @param card_id           微信卡券ID（此ID为微信生成的card_id）
	 * @param wxId			  	微信平台ID
	 * @return
	 */
	public Object createWxmultipleWithQrcode(List<String> cardIdList,String wxId){
		Map<String,Object> map=new HashMap<String,Object>();
		
		try {
			//1.组装数据
			Map<String,Object> multipleCardMap=new HashMap<String,Object>();
			List<Map<String,Object>> card_list=new ArrayList<Map<String,Object>>();
			for(String card_id:cardIdList){
				Map<String,Object> idMap=new HashMap<String,Object>();
				idMap.put("card_id",card_id);
				card_list.add(idMap);
			}
			multipleCardMap.put("card_list", card_list);
			Map<String,Object> actionInfoMap=new HashMap<String,Object>();
			actionInfoMap.put("multiple_card", multipleCardMap);
			Map<String,Object> paramMap=new HashMap<String,Object>();
			paramMap.put("action_info", actionInfoMap);
			paramMap.put("action_name", "QR_MULTIPLE_CARD");
			//2.发起请求
			WxMpService wxMpService=getWxMpService(wxId);
			String token=wxMpService.getAccessToken();
			
			System.out.println("=============="+JSONObject.fromObject(paramMap).toString());
			String url="https://api.weixin.qq.com/card/qrcode/create?access_token="+token;
			JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", JSONObject.fromObject(paramMap).toString());
			
			map.put("code", "1");
			map.put("message", "创建成功");
			map.put("data", jsonObject);
			return map;
		} catch (Exception e) {
			map.put("code", "0");
			map.put("message", e.getMessage());
			return map;
		}
	}
	
	/**
	 * 创建微信卡券货架
	 * @param wxId			  		微信平台ID
	 * @param card_list
	 * @param banner                页面的banner图片链接，须调用，建议尺寸为640*300。
	 * @param page_title			页面的title
	 * @param can_share				页面是否可以分享,填入true/false
	 * @param scene					投放页面的场景值；SCENE_NEAR_BY 附近 SCENE_MENU	自定义菜单 SCENE_QRCODE	二维码 SCENE_ARTICLE	公众号文章 SCENE_H5	h5页面 SCENE_IVR	自动回复 SCENE_CARD_CUSTOM_CELL	卡券自定义cell
	 * @return
	 */
	public Map<String,Object> createWxlandingPage(String wxId,List<LandingPage> card_list,String banner,String page_title,boolean can_share,String scene ){
		
		/*LandingPage landingPage=new LandingPage();
		LandingPage landingPage1=new LandingPage();
		landingPage.setCard_id("pqDfiwxTU_exuerX2nVRtAmO8-Ms");
		landingPage1.setCard_id("pqDfiw6gN5OK5nGfJC2b3SVrLlzE");
		landingPage.setThumb_url("http://mmbiz.qpic.cn/mmbiz_jpg/6WyzMOGpyNDfGaibic4UKoszSW86T7Mt7T4VpkebwMFYL8XoDlDNDTtov6HDJE7Xgn9NtqbenYAzu3dibeRSwfYDA/0");
		landingPage1.setThumb_url("http://mmbiz.qpic.cn/mmbiz_jpg/6WyzMOGpyNDfGaibic4UKoszSW86T7Mt7T4VpkebwMFYL8XoDlDNDTtov6HDJE7Xgn9NtqbenYAzu3dibeRSwfYDA/0");
		List<LandingPage> card_list=new ArrayList<LandingPage>();
		
		card_list.add(landingPage);
		card_list.add(landingPage1);
		
		String banner="http://mmbiz.qpic.cn/mmbiz_jpg/6WyzMOGpyNDfGaibic4UKoszSW86T7Mt7T4VpkebwMFYL8XoDlDNDTtov6HDJE7Xgn9NtqbenYAzu3dibeRSwfYDA/0";*/
		Map<String,Object> map=new HashMap<String,Object>();
		try {
			//1.组装数据
			Map<String,Object> paramMap=new HashMap<String,Object>();
			paramMap.put("banner", banner);
			paramMap.put("page_title",page_title);
			paramMap.put("scene", scene);
			paramMap.put("can_share", true);
			paramMap.put("card_list", card_list);
			//2.发起请求
			WxMpService wxMpService=getWxMpService(wxId);
			String token=wxMpService.getAccessToken();
			
			System.out.println("=============="+JSONObject.fromObject(paramMap).toString());
			String url="https://api.weixin.qq.com/card/landingpage/create?access_token="+token;
			JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", JSONObject.fromObject(paramMap).toString());
			
			map.put("code", "1");
			map.put("message", "创建成功");
			map.put("data", jsonObject);
			return map;
		} catch (Exception e) {
			map.put("code", "0");
			map.put("message", e.getMessage());
			return map;
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 获取微信公众号服务
	 * 
	 * @param wxid
	 * @return
	 */
	public WxMpService getWxMpService(String wxid) {
		WxMpConfigStorage config = getWxConfig(wxConfigService.fetch(wxid));
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);
		return wxMpService;
	}
	/**
	 * 获取公众号配置
	 * 
	 * @param appInfo
	 * @return
	 */
	public WxMpConfigStorage getWxConfig(Wx_config appInfo) {
		if (null == appInfo)
			return null;
		WxMpConfigStorage config = new WxMpInMemoryConfigStorage();
		((WxMpInMemoryConfigStorage) config).setAppId(appInfo.getAppid()); // 设置微信公众号的appid
		((WxMpInMemoryConfigStorage) config).setSecret(appInfo.getAppsecret()); // 设置微信公众号的app
		((WxMpInMemoryConfigStorage) config).setToken(appInfo.getToken()); // 设置微信公众号的token
		((WxMpInMemoryConfigStorage) config).setAesKey(appInfo.getEncodingAESKey()); // 设置微信公众号的EncodingAESKey

		return config;
	}


	@Aop(TransAop.READ_COMMITTED)
	public void insertCard(Ud_wx_card card_info) {
		dao().insert(card_info);
		//数据同步到ud_card
		Ud_card card=new Ud_card();
		Subject subject = SecurityUtils.getSubject();
        Sys_user user = (Sys_user) subject.getPrincipal();
		card.setCompany_id(user.getUnit().getCompany_id());
		card.setCreateAt(card_info.getCreate_time());
		card.setRawid(card_info.getCard_id());
		card.setSource("微信");
		card.setState(0);
		card.setType(card_info.getCard_type());
		cardService.insert(card);
		
	}


	/**
	 * 卡券核销
	 * 
	 * @param card_id
	 * @param card_code
	 * @param string 
	 * @param appId
	 */
	@Aop(TransAop.READ_COMMITTED)
	public void consume(String wxId,String openId,String card_id,String card_code) {
		WxMpService wxMpService=getWxMpService(wxId);
		//判断是否已经核销
		Cnd cnd=Cnd.NEW();
		cnd.and("card_id", "=", card_id);
		cnd.and("card_code", "=", card_code);
		Ud_card_review card_review = cardReviewService.fetch(cnd);
		if (null == card_review) {
			card_review = new Ud_card_review();
			card_review.setCard_code(card_code);
			card_review.setCard_id(card_id);
			card_review.setUser_type(UserTypeEnum.WEIXIN.code());
			card_review.setUser_id(openId);
			card_review.setState(2);
			card_review.setReview_time((int) (System.currentTimeMillis() / 1000));
			cardReviewService.insert(card_review);
		}

		try {
			String token = wxMpService.getAccessToken();
			String url = "https://api.weixin.qq.com/card/code/get?access_token=" + token;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("card_id", card_id);
			map.put("code", card_code);
			map.put("check_consume", true);

			JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", JSONObject.fromObject(map).toString());
			Integer errcode = jsonObject.getInt("errcode");
			if (errcode == 0) {
				String user_card_status = jsonObject.getString("user_card_status");
				if (user_card_status != null && user_card_status.equals("NORMAL")) {
					String token1 = wxMpService.getAccessToken();
					String consumeUrl = "https://api.weixin.qq.com/card/code/consume?access_token=" + token1;
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("code", card_code);
					JSONObject jsonObject1 = HttpUtils.httpRequest(consumeUrl, "POST",
							JSONObject.fromObject(map1).toString());
					Integer errcode1 = jsonObject.getInt("errcode");
					if (errcode1 == 0) {
						card_review.setState(1);
						cardReviewService.update(card_review);
					}
				}
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
		}

	}

}
